import React, { useEffect } from 'react';
import { Button, Input, Radio, Spin } from 'antd';
import { useSetState } from 'ahooks';
import moment from 'moment';

import { TRMessage } from '#/components';
import { createFromIconfontCN } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts.js';
import renovate from '#/utils/renovate';
import { AntdBaseTable } from '@/base/TBaseTable';

import { getAdjustData, computeData, saveData } from '../../service';
import Charts from '../Charts';
import { getCharts } from '../Charts/helper';
import {
  comlumnsRender,
  RADIOCHECK,
  initData,
  iconUrl,
  tableStyle,
  deleteTable,
  checkTable,
  changeTime,
  TIMEOBJ,
  generaTime,
  changeVal,
  DATATYPE,
  onBlurFn,
  addFn,
  AdjustToolFn,
  initComputeData,
  useBtnJurisdiction,
} from './helper';
import styles from './index.less';

const MyIcon = createFromIconfontCN({
  scriptUrl: iconUrl,
});

export default function Adjust({
  rangeDate,
  supplyDate,
  stationIds,
  afterComputeFn,
  isFresh,
  buttonPermissions,
}) {
  const TIMEFORMAT = 'YYYY-MM-DD';
  const [state, setState] = useSetState({
    data: [],
    capacity: 0,
    adjusTool: [],
    spinLoading: false,
    btnLoading: false,
  });
  const hasSave = useBtnJurisdiction(buttonPermissions);
  useEffect(() => {
    if (rangeDate.length && supplyDate.length) {
      fetchData();
    }
  }, [rangeDate, supplyDate, isFresh]);
  const fetchData = async () => {
    setState({ spinLoading: true });
    const _stationIds = stationIds.map((item) => item.stationId);
    let res = await getAdjustData({
      declareDate: moment(rangeDate).format(TIMEFORMAT),
      targetDate: moment(supplyDate).format(TIMEFORMAT),
      gId: null,
      stationIds: _stationIds,
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      const data = initData(res?.data?.details || []);
      setState({
        data,
        capacity: res?.data?.capacity || 0,
        spinLoading: false,
      });
    }
  };
  /*  时间段输入 */
  const handelTime = (e, allVal, key) => {
    const _data = changeTime(e, allVal, key, state.data);
    setState({ data: _data });
  };
  /*  时间段失焦 */
  const handelBlur = (e, allVal, key) => {
    const _data = generaTime(e?.target?.value || '', allVal, key, state.data);
    setState({ data: _data });
  };
  /* 单选框选择 */
  const handelRadio = (id, key) => {
    const _data = checkTable(id, state.data, key);
    setState({ data: _data });
  };
  /* 删除 */
  const handelDelete = (id) => {
    const _data = deleteTable(id, state.data);
    setState({ data: _data });
  };
  /* 输入最大值最小值固定值 */
  const handelInput = (key, allVal, e) => {
    const _data = changeVal(key, allVal, e, state.data);
    setState({ data: _data });
  };
  /* 失焦最大值最小值固定值 */
  const handelBlurInput = (key, allVal, e) => {
    const { data, capacity } = state;
    renovate.isRenovate = true;
    const _data = onBlurFn(key, allVal, e, data, capacity);
    setState({ data: _data });
  };
  /* 添加 */
  const handelAdd = () => {
    const { data, capacity } = state;
    const _data = addFn(data, capacity);
    setState({ data: _data });
  };
  /* toolTip改变 */
  const handelTool = (val) => {
    setState({
      adjusTool: val,
    });
  };
  /* 保存 */
  const handelSave = async () => {
    renovate.isRenovate = false;
    if (!hasSave) {
      TRMessage.info('请联系管理员获取相关权限');
      return;
    }
    let res = await handelSaveOrCompute(saveData);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({ btnLoading: false });
      fetchData();
      handelCompute();
    }
  };
  /*封装保存计算函数 */
  const handelSaveOrCompute = async (func) => {
    setState({ btnLoading: true });
    const { data, capacity } = state;
    const _data_ = initComputeData(data);
    const stationData = stationIds.map((item) => item?.stationId || '');
    let res = await func({
      capacity,
      declareDate: moment(rangeDate).format(TIMEFORMAT),
      targetDate: moment(supplyDate).format(TIMEFORMAT),
      stationIds: stationData,
      details: _data_,
    });
    return res;
  };
  /*计算 */
  const handelCompute = async (func) => {
    let res = await handelSaveOrCompute(computeData);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({ btnLoading: false });
      afterComputeFn && afterComputeFn(res?.data || []);
    }
  };
  //渲染表格
  const columnsMain = (val, allVal, key, index) => {
    const { data } = state;
    if (key === 'first') {
      return (
        <div className={styles.firstColumn} key={index}>
          <span>{allVal?._index}</span>
          <span>
            <font className={styles.timeval}>
              <Input
                value={allVal?.beginIndex}
                onChange={(e) => handelTime(e, allVal, TIMEOBJ['BEGIN'])}
                onBlur={(e) => handelBlur(e, allVal, TIMEOBJ['BEGIN'])}
              />
              -
              <Input
                value={allVal?.endIndex}
                onChange={(e) => handelTime(e, allVal, TIMEOBJ['END'])}
                onBlur={(e) => handelBlur(e, allVal, TIMEOBJ['END'])}
              />
            </font>
          </span>
        </div>
      );
    } else if (key === 'second') {
      const disabled = allVal?.useType != RADIOCHECK['DATASOURCE'];
      // changeTime
      return (
        <div className={styles.secondColumn} key={index}>
          <span>
            <Radio
              checked={!disabled}
              onClick={() => handelRadio(allVal?.id, RADIOCHECK['DATASOURCE'])}
            />
            <Input
              value={String(allVal?.rateValue) || ''}
              disabled={disabled}
              onChange={(e) => handelInput(DATATYPE['RATEVALUE'], allVal, e)}
              onBlur={(e) => handelBlurInput(DATATYPE['RATEVALUE'], allVal, e)}
            />
          </span>
          <span>
            <Input
              value={String(allVal?.maxValue) || ''}
              disabled={disabled}
              onChange={(e) => handelInput(DATATYPE['MAXVALUE'], allVal, e)}
              onBlur={(e) => handelBlurInput(DATATYPE['MAXVALUE'], allVal, e)}
            />
          </span>
          <span>
            <Input
              value={String(allVal?.minValue) || ''}
              disabled={disabled}
              onChange={(e) => handelInput(DATATYPE['MINVALUE'], allVal, e)}
              onBlur={(e) => handelBlurInput(DATATYPE['MINVALUE'], allVal, e)}
            />
          </span>
        </div>
      );
    } else if (key === 'third') {
      const disabled = allVal?.useType === RADIOCHECK['FIXATION'];
      return (
        <div className={styles.thirdColumn} key={index}>
          <span>
            <Radio
              checked={disabled}
              onClick={() => handelRadio(allVal?.id, RADIOCHECK['FIXATION'])}
            />
            <Input
              value={allVal?.fixedValue}
              disabled={!disabled}
              onChange={(e) => handelInput(DATATYPE['FIXEDVALUE'], allVal, e)}
              onBlur={(e) => handelBlurInput(DATATYPE['FIXEDVALUE'], allVal, e)}
            />
          </span>
        </div>
      );
    } else {
      return (
        <MyIcon
          key={index}
          type={'iconshanchu'}
          style={{ color: '#EB5757' }}
          onClick={() => handelDelete(allVal?.id)}
        />
      );
    }
  };
  const { data, adjusTool, spinLoading, btnLoading } = state;
  if (spinLoading)
    return (
      <div className={styles.spinBox}>
        <Spin />
      </div>
    );
  return (
    <div>
      <div className={styles.title}>
        <div className={styles.titleLeft}>
          调整比例
          <font className={styles.subTitle}>
            (结算单元没有的预测数据源以及未选择的时间段会用默认数据源进行代替)
          </font>
        </div>
        <div className={styles.btnGroup}>
          <Button onClick={handelAdd} loading={btnLoading}>
            添加
          </Button>
          <Button type="primary" onClick={handelCompute} loading={btnLoading}>
            计算
          </Button>
          <Button
            type="primary"
            onClick={handelSave}
            loading={btnLoading}
            className={!hasSave ? styles.savegray : ''}
          >
            保存
          </Button>
        </div>
      </div>
      <div className={styles.mainBox}>
        <div className={styles.mainLeft}>
          {AdjustToolFn(adjusTool)}
          <Charts config={getCharts('ADJUST_SCALE', data, handelTool)} />
        </div>
        <div className={styles.mainRight}>
          <AntdBaseTable
            columns={comlumnsRender(columnsMain)}
            dataSource={data}
            // style={tableStyle}
          />
        </div>
      </div>
      <div />
    </div>
  );
}
